// utils/downloadUtil.js

/**
 * 下载单张图片并保存到相册
 * @param {Object} image - 图片对象 {id: string, url: string}
 * @param {Object} options - 配置项 {headers: Object, onProgress: Function}
 * @returns {Promise} 
 */
export async function downloadSingleImage(image, options = {}) {
  try {
    // 1. 下载图片到临时文件
    const { tempFilePath } = await downloadFile(image.url, options.headers);
    console.log(tempFilePath,'tempFilePath');
    
    // 2. 保存到相册
    await saveToAlbum(tempFilePath);
    
    // 3. 记录下载成功（可选）
    // await recordDownload(image.id);
    
    return {
      success: true,
      imageId: image.id,
      tempFilePath
    };
  } catch (error) {
    console.error(`图片下载失败 [${image.id}]:`, error);
    return {
      success: false,
      imageId: image.id,
      error: error.message || '下载失败'
    };
  }
}

// 下载文件到临时路径
function downloadFile(url, headers) {
  return new Promise((resolve, reject) => {
    const task = uni.downloadFile({
      url,
      header: headers || {},
      success: resolve,
      fail: reject
    });
    
    // 进度回调（可选）
    // if (options && options.onProgress) {
    //   task.onProgressUpdate(options.onProgress);
    // }
  });
}

// 保存到相册
function saveToAlbum(tempFilePath) {
  return new Promise((resolve, reject) => {
    // 检查权限
    uni.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          uni.authorize({
            scope: 'scope.writePhotosAlbum',
            success: () => saveImage(tempFilePath, resolve, reject),
            fail: () => reject(new Error('用户拒绝了相册权限'))
          });
        } else {
          saveImage(tempFilePath, resolve, reject);
        }
      },
      fail: reject
    });
  });
}

// 实际保存操作
function saveImage(tempFilePath, resolve, reject) {
  uni.saveImageToPhotosAlbum({
    filePath: tempFilePath,
    success: resolve,
    fail: reject
  });
}

// 记录下载（可选）
function recordDownload(imageId) {
  return uni.request({
    url: '/api/record-download',
    method: 'POST',
    data: { imageId }
  });
}